package service;

import com.alibaba.fastjson.JSONObject;
import dao.BookMapper;
import dao.CartMapper;
import entity.Book;
import entity.BookExample;
import entity.Cart;
import entity.CartExample;
import enums.CartEnum;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import vo.ResultVO;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 购物车服务
 * Created by weijianyu on 2017/5/19.
 */
@Service
public class CartService {

    private static final Logger logger = LogManager.getLogger(CartService.class);

    private final CartMapper cartMapper;
    private final BookMapper bookMapper;

    /**
     * 构造方法
     * 初始化
     *
     * @param cartMapper 购物车dao层服务
     * @param bookMapper 书籍dao层服务
     */
    @Autowired
    public CartService(CartMapper cartMapper, BookMapper bookMapper) {
        Assert.notNull(cartMapper, "cartMapper must not null!");
        this.cartMapper = cartMapper;
        Assert.notNull(bookMapper, "bookMapper must not null!");
        this.bookMapper = bookMapper;
    }

    /**
     * 添加到购物车
     *
     * @param cart 添加的信息
     * @return 返回是否成功
     */
    public ResultVO<JSONObject> add(Cart cart) {
        ResultVO<JSONObject> result = new ResultVO<JSONObject>();

        ResultVO<JSONObject> vail = vailCart(cart);
        if (vail != null) {
            return vail;
        }

        CartExample cartExample = new CartExample();
        cartExample.or().andUserIdEqualTo(cart.getUserId()).andBookIdEqualTo(cart.getBookId()).andIsDeleteEqualTo((short) 0);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        if (carts.isEmpty()) {
            int col = cartMapper.insertSelective(cart);
            if (col > 0) {
                JSONObject data = new JSONObject();
                data.put("item", cart);
                result.setCode(CartEnum.ADD_SUCCESS.getCode());
                result.setData(data);
                result.setErrorMessage("");
                return result;
            } else {
                logger.error("购物车 添加到购物车失败");
                result.setCode(CartEnum.ERROR.getCode());
                result.setErrorMessage("添加到购物车失败，请联系后台管理");
                return result;
            }
        } else {
            if (carts.size() == 1) {
                Cart update = carts.get(0);
                update.setAmount((short) (update.getAmount() + cart.getAmount()));
                int col = cartMapper.updateByPrimaryKey(update);
                if (col > 0) {
                    logger.info("更新源记录成功");
                    JSONObject data = new JSONObject();
                    data.put("item", update);
                    result.setCode(CartEnum.ADD_SUCCESS.getCode());
                    result.setData(data);
                    result.setErrorMessage("");
                    return result;
                } else {
                    logger.error("购物车 更新数量出错");
                    result.setCode(CartEnum.ERROR.getCode());
                    result.setErrorMessage("数据库错误，请联系管理!");
                    return result;
                }
            } else {
                logger.error("购物车 数据库信息错误 {}", carts);
                result.setCode(CartEnum.ERROR.getCode());
                result.setErrorMessage("数据库错误，请联系管理!");
                return result;
            }
        }
    }

    /**
     * 购物车列表展示
     *
     * @param cart 用户信息
     * @return 购物车列表展示信息
     */
    public ResultVO<JSONObject> list(Cart cart) {
        ResultVO<JSONObject> result = new ResultVO<JSONObject>();
        JSONObject data = new JSONObject();

        if (cart.getUserId() == null) {
            result.setCode(CartEnum.CART_USER.getCode());
            result.setErrorMessage(CartEnum.CART_USER.getMessage());
            return result;
        }

        CartExample cartExample = new CartExample();
        cartExample.or().andUserIdEqualTo(cart.getUserId()).andIsDeleteEqualTo((short) 0);
        List<Cart> cartList = cartMapper.selectByExample(cartExample);
        if (cartList.isEmpty()) {
            logger.info("购物车为空！");
            result.setCode(CartEnum.SUCCESS.getCode());
            result.setErrorMessage("");
            return result;
        }

        data.put("cartList", cartList);
        BookExample bookExample = new BookExample();
        List<Integer> ids = new ArrayList<Integer>();
        for (Cart item : cartList) {
            ids.add(item.getBookId());
        }
        bookExample.or().andIdIn(ids);
        List<Book> books = bookMapper.selectByExample(bookExample);
        if (books.isEmpty()) {
            logger.error("购物车 查询不到书籍");
        }
        data.put("books", books);
        result.setCode(CartEnum.SUCCESS.getCode());
        result.setData(data);
        result.setErrorMessage("");
        return result;
    }

    /**
     * 删除商品
     *
     * @param cart 要删除的商品
     * @return 信息
     */
    public ResultVO<String> delete(Cart cart) {
        ResultVO<String> result = new ResultVO<String>();

        if (cart.getId() == null) {
            result.setCode(CartEnum.DELETE_ID.getCode());
            result.setErrorMessage(CartEnum.DELETE_ID.getMessage());
            return result;
        }

        cart.setIsDelete((short) 1);
        int col = cartMapper.updateByPrimaryKeySelective(cart);
        if (col == 1) {
            result.setCode(CartEnum.SUCCESS.getCode());
            result.setData("删除成功");
            result.setErrorMessage("");
            return result;
        } else {
            logger.error("删除出错");
            result.setCode(CartEnum.ERROR.getCode());
            result.setErrorMessage("删除出错");
            return result;
        }
    }


    /**
     * 购物车数据校验
     *
     * @param cart 前端信息
     * @return 返回校验信息 成功返回空
     */
    private ResultVO<JSONObject> vailCart(Cart cart) {
        ResultVO<JSONObject> vail = new ResultVO<JSONObject>();

        if (cart.getUserId() == null) {
            vail.setCode(CartEnum.VAIL_USER.getCode());
            vail.setErrorMessage(CartEnum.VAIL_USER.getMessage());
            return vail;
        }
        if (cart.getBookId() == null) {
            vail.setCode(CartEnum.VAIL_BOOK.getCode());
            vail.setErrorMessage(CartEnum.VAIL_BOOK.getMessage());
            return vail;
        }
        if (cart.getAmount() == null) {
            vail.setCode(CartEnum.VAIL_AMOUNT.getCode());
            vail.setErrorMessage(CartEnum.VAIL_AMOUNT.getMessage());
            return vail;
        }
        return null;
    }
}
